import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/provider_scaffold.dart';
import 'package:gold/ui/my/order/order_detail_viewmodel.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 订单详情
/// @author tangzhentao
/// @created at 22:41 2025/2/28

class OrderDetailPage extends StatelessWidget {
  /// 商品类型
  final String orderType;
  /// 订单ID
  final int orderId;

  const OrderDetailPage({super.key, required this.orderType, required this.orderId});

  @override
  Widget build(BuildContext context) {
    return ProviderScaffold<OrderDetailViewmodel>(
      appBar: (_) => xfgAppbar(title: '详情'),
      model: OrderDetailViewmodel(orderType, orderId),
      onInit: (data) => data.load(),
      builder: (ctx, detail) {
        final order = detail.order;
        /// 计算单价
        final price = order?.detail?.product?.price?? 0.0;
        final points = order?.detail?.product?.pointsPrice?? 0;
        String priceDesc;
        if (orderType == ProductType.points) {
          priceDesc = '${price > 0 ? '¥${price.toStringAsFixed(2)} + ':''}$points积分';
        } else {
          priceDesc = '¥${price.toStringAsFixed(2)}';
        }
        /// 计算实际支付
        String realPriceDesc;
        if (orderType == ProductType.points) {
          final rlPrice = ((order?.totalPrice?? 0.0) + (order?.freight?? 0.0));
          final rlPoints = order?.pointsNum?? 0;
          realPriceDesc = '${rlPrice > 0 ? '¥${rlPrice.toStringAsFixed(2)} + ':''}$rlPoints积分';
        } else {
          final rlPrice = (order?.payPrice?? 0.00) + (order?.amountNum?? 0.00);
          final rlPoints = order?.pointsNum?? 0;
          realPriceDesc = '¥${rlPrice.toStringAsFixed(2)}${rlPoints > 0 ? ' + $rlPoints积分':''}';
        }
        return Padding(
          padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().bottomBarHeight == 0 ?  XfgSize().size24:XfgSize().bottomBarHeight),
          child: Column(
            children: [
              Expanded(
                child: Container(
                  decoration: white6Decoration,
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.only(left: XfgSize().size14, top: XfgSize().size16),
                          alignment: Alignment.centerLeft,
                          child: XfgText(order?.shop?.name?? '', fontSize: XfgSize().text18, color: XfgColor.text1, bold: FontWeight.w600),
                        ),
                        /// 商品信息
                        Container(
                          margin: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().size15),
                          height: XfgSize().size100,
                          child: Row(
                            children: [
                              HttpImage(order?.detail?.product?.coverImage, size: Size.square(XfgSize().size100), radius: BorderRadius.circular(XfgSize().size6)),
                              SizedBox(width: XfgSize().size14),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    XfgText(order?.detail?.product?.name?? '', fontSize: XfgSize().text16, color: XfgColor.text2, maxLines: 1, overflow: TextOverflow.ellipsis),
                                    SizedBox(height: XfgSize().size16),
                                    Row(
                                      children: [
                                        XfgText('单价：', fontSize: XfgSize().text14, color: XfgColor.text2),
                                        XfgText(priceDesc, fontSize: XfgSize().text16, color: XfgColor.theme, bold: FontWeight.bold),
                                        const Spacer(),
                                        XfgText('x${order?.quantity?? 1}', fontSize: XfgSize().text16, color: XfgColor.text1D),
                                      ],
                                    ),
                                    SizedBox(height: XfgSize().size16),
                                    Container(
                                      height: XfgSize().size18,
                                      width: XfgSize().size12 + boundingTextSize('不支持七天无理由', style: TextStyle(fontSize: XfgSize().text12)).width,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                          border: Border.all(color: XfgColor.itemIntegration, width: XfgSize().size0_5),
                                          borderRadius: BorderRadius.circular(XfgSize().size2)
                                      ),
                                      child: XfgText('不支持七天无理由', fontSize: XfgSize().text12, color: XfgColor.itemIntegration),
                                    )
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                        strokeHeightContainer,
                        Container(
                          height: XfgSize().size50,
                          padding: EdgeInsets.only(left: XfgSize().size12, right: XfgSize().size8),
                          child: Row(
                            children: [
                              Visibility(
                                visible: orderType != ProductType.points,
                                child: XfgText('共优惠', fontSize: XfgSize().text14, color: XfgColor.text1, children: [
                                  TextSpan(text:'¥0', style: TextStyle(color: XfgColor.theme)),
                                ]),
                              ),
                              const Spacer(),
                              XfgText('实际支付', fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
                              SizedBox(width: XfgSize().size16),
                              XfgText(realPriceDesc, fontSize: XfgSize().text14, color: XfgColor.theme, bold: FontWeight.bold),
                            ],
                          ),
                        ),
                        strokeHeightContainer,
                        Visibility(
                          visible: orderType != ProductType.points,
                          child: _itemWidget('积分抵扣', '${order?.pointsNum?? 0}个', valueColor: XfgColor.text1D),
                        ),
                        _itemWidget('余额抵扣', '¥${order?.amountNum?? 0.00}', valueColor: XfgColor.text1D),
                        strokeHeightContainer,
                        _itemCopyWidget('订单编号', order?.orderNo),
                        _itemWidget('交易快照', '发生争议时，可作为依据'),
                        _itemWidget('支付方式', '微信支付'),
                        _itemWidget('支付时间', order?.createdAt?? ''),
                        _itemWidget('收货时间', order?.receivedAt?? '--'),
                        strokeHeightContainer,
                        _itemCopyWidget('快递单号', order?.express?.expressDetail?.mailNo),
                        _itemWidget('配送方式', order?.express?.expressDetail?.expTextName?? '--'),
                        _itemWidget('收货地址', '${order?.address?.address?? ''}${order?.address?.houseNumber?? ''}'),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(height: XfgSize().size16),
              Row(mainAxisAlignment: MainAxisAlignment.end, children: _getButtons(detail))
            ],
          ),
        );
      },
    );
  }

  /// 获取按钮集合
  List<Widget> _getButtons(OrderDetailViewmodel detail) {
    final List<Widget> buttons = [
      TextButton(
          onPressed: detail.checkLogistics,
          style: _buttonStyle(XfgColor.colorF2),
          child: XfgText('查看物流', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
      ),
      SizedBox(width: XfgSize().size10),
    ];
    if (detail.order?.status == OrderStatus.sending || detail.order?.refundStatus == RefundStatus.applying) {
      buttons.addAll([
        TextButton(
            onPressed: detail.handleRefund,
            style: _buttonStyle(XfgColor.colorF2),
            child: XfgText('退换/售后', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold)
        ),
        SizedBox(width: XfgSize().size10),
      ]);
    }
    buttons.addAll([
      TextButton(
          onPressed: detail.buyAgain,
          style: _buttonStyle(XfgColor.theme),
          child: XfgText('再次购买', fontSize: XfgSize().text14, color: XfgColor.white, bold: FontWeight.bold)
      ),
      SizedBox(width: XfgSize().size10),
    ]);
    return buttons;
  }

  /// 通用信息
  Widget _itemWidget(String text, String value, {Color? valueColor}) => Container(
    padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size12, XfgSize().size12, XfgSize().size8),
    child: Row(
      children: [
        XfgText(text, fontSize: XfgSize().text14, color: XfgColor.text1D),
        SizedBox(width: XfgSize().size24),
        Expanded(child: XfgText(value, fontSize: XfgSize().text14, color: valueColor?? XfgColor.text3, textAlign: TextAlign.end, height: 1.3))
      ],
    ),
  );

  /// 可复制的通用信息
  Widget _itemCopyWidget(String text, String? value) => Container(
    padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size12, XfgSize().size12, XfgSize().size8),
    child: Row(
      children: [
        XfgText(text, fontSize: XfgSize().text14, color: XfgColor.text1D),
        Expanded(child: XfgText(value?? '--', fontSize: XfgSize().text14, color: XfgColor.text3, textAlign: TextAlign.end)),
        Visibility(
          visible: value?.isNotEmpty == true,
          child: Container(
            margin: EdgeInsets.only(left: XfgSize().size10),
            child: Builder(builder: (con) => GestureDetector(
              onTap: () {
                Clipboard.setData(ClipboardData(text: value?? '')).then((_) {
                  xfgShowSnackBar(con, text, value?? '');
                });
              },
              child: XfgText('复制', fontSize: XfgSize().text14, color: XfgColor.text1D),
            )),
          ),
        )
      ],
    ),
  );

  /// 按钮 装饰器
  ButtonStyle _buttonStyle(Color color) => ButtonStyle(
      backgroundColor: WidgetStatePropertyAll(color),
      shape: WidgetStatePropertyAll(RoundedRectangleBorder(borderRadius: BorderRadius.circular(XfgSize().size40))),
      fixedSize: WidgetStatePropertyAll(Size(XfgSize().size97, XfgSize().size40))
  );
}
